
import 'dart:io';

import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_app_common_bar.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/pages/home/models/val_coin_list_info_model.dart';
import 'package:valovault_reminder/pages/home/views/val_reminder_coin_shop_amount_cell.dart';
import 'package:flutter/material.dart';

import '../../common/bean/val_user_base_info_model.dart';
import '../../common/util/val_apple_pay_tool.dart';
import '../../common/util/val_logger_manager.dart';
import '../../util/val_eventbus_manager.dart';
import 'components/val_reminder_coin_shop_grid_cell.dart';

class ValReminderCoinShopPage extends StatefulWidget {
  const ValReminderCoinShopPage({super.key});

  @override
  State<ValReminderCoinShopPage> createState() => _ValReminderCoinShopPageState();
}

class _ValReminderCoinShopPageState extends ValBaseUIPageState<ValReminderCoinShopPage> {
  int userCoin = 0;
  List<ValCoinListInfoModel> coinGoodsList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = true;
    extendBodyBehindAppBar = true;
    userCoin = ValAppStateTool().accountInfo!.availableCoins;
    loadCoinGoodsDataPost();

    ValLoggerManager.stat(page: ValConfigLoggerPath.purchase);
  }

  @override
  PreferredSizeWidget? get appBar {
    return ValAppCommonBar(
      backgroundColor: Colors.transparent,
      title: 'Coin Shop',
      titleColor: Colors.white,
      brightness: Brightness.dark,
      leadingWidget: GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Image.asset(
            '${ValAssetsName.ASSETS_HOME}val_common_nav_back.png',
            width: 30,
            height: 30,
          )
      ),
    );
  }

  //商品列表
  void loadCoinGoodsDataPost() {
    String payChannel = Platform.isIOS ? 'IAP' : 'GP';
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.coinGoodsSearch, {"isIncludeSubscription": false, "payChannel": payChannel},
            (data, errorCode, message){
          if (errorCode == 0 && data != null) {
            List<ValCoinListInfoModel> coinList = [];
            for(int index = 0; index < data.length; index ++) {
              Map<String, dynamic> map = data[index];
              if (!map.containsKey('tags')) {
                map['tags'] = '';
              }
              ValCoinListInfoModel goodsModel = ValCoinListInfoModel.fromJson(map);
              coinList.add(goodsModel);
            }
            setState(() {
              coinGoodsList.addAll(coinList);
            });
          }
        }, (err){

        });
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFF080822),
        body: Container(
          decoration: const BoxDecoration(
            color: Color(0xFF080822),
            image: DecorationImage(
                image: AssetImage('${ValAssetsName.ASSETS_Message}val_coin_shop_ground.png'), fit: BoxFit.fill),
          ),
          child: Column(
            children: [
              if (coinGoodsList.isNotEmpty)
                ValReminderCoinShopAmountCell(accountNumber: '$userCoin',),
              Expanded(child: coinGoodsCollection()),
            ],
          ),
        )
    );
  }

  Widget coinGoodsCollection() {
    return GridView.builder(
      padding: const EdgeInsets.only(top: 20, bottom: 10, left: 24, right: 24),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3, //列数
        childAspectRatio: 0.58,//102.0/148.0, //显示区域宽高相等
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ),
      itemCount: coinGoodsList.length,
      itemBuilder: (BuildContext content, int position) {
        ValCoinListInfoModel goodsModel = coinGoodsList[position];
        // if (position == 0) {
        //   return ValReminderCoinShopAmountCell(accountNumber: '$userCoin',);
        // }
        return ValReminderCoinShopGridCell(exchangeCoin: "${goodsModel.exchangeCoin}",
          discount: goodsModel.discount,
          price: "${goodsModel.price}",
          originPrice: "${goodsModel.originalPrice}",
          hotTag: goodsModel.tags.isNotEmpty ? goodsModel.tags.toUpperCase().contains('HOT') : false,
          onTap: () {
            /// 后台生成订单
            ValApplePayTool().createOrder(goodsModel.code, (data) {
              ValLoggerManager.stat(page: ValConfigLoggerPath.createorder);
              /// 开启苹果支付
              // print('=====生成订单=========');
              // print('=====$data=========');
              // print('=====${data['orderNo']}=========');

              ValApplePayTool().applePay(data, () async {
                ValAppStateTool.getUserInfo(refresh: true,completion: (ValUserBaseInfoModel? u) {
                  userCoin = u?.availableCoins ?? 0;
                  ValAppStateTool().accountInfo?.availableCoins =  u?.availableCoins ??0;
                  ValEventbusManager.getInstance().eventBus.fire('coinCharged');
                  setState(() {

                  });
                });

              });
            });
            /// 生成订单
            // print('=====xxxx==xxxx====xxxx===xxxxx');
          },
        );
      },
    );
  }
}
